package com.todod.service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.todod.common.util.SnowflakeIdGenerator;
import com.todod.mapper.ProjectInfoMapper;
import com.todod.mapper.ProjectInfoRecordsMapper;
import com.todod.model.ProjectInfo;
import com.todod.model.ProjectInfoRecords;
import com.todod.model.User;

@Service
@Transactional
public class ProjectInfoRecordsService {

	@Autowired
	private ProjectInfoRecordsMapper projectInfoRecordsMapper;
	@Autowired
	private IUserService iUserService;
	@Autowired
	private ProjectInfoMapper projectInfoMapper;

	/**
	 * @author dyl
	 * @date 2023-08-22
	 * @param userId
	 * @param projectInfoRecords
	 */
	public void saveData(Long userId, ProjectInfoRecords projectInfoRecords) {

		projectInfoRecords.setId(SnowflakeIdGenerator.getId());

		projectInfoRecords.setCreateTime(LocalDateTime.now());
		projectInfoRecords.setCreateUserId(userId);

		ProjectInfo projectInfo = projectInfoMapper.selectById(projectInfoRecords.getProjectId());

		projectInfo.setStatus(projectInfoRecords.getResult());
		projectInfo.setModifytimeTi(LocalDateTime.now());
		projectInfo.setModifyuserId(userId);
		projectInfoMapper.updateById(projectInfo);

		projectInfoRecordsMapper.insert(projectInfoRecords);
	}

	public List<ProjectInfoRecords> getListByProjectId(Long projectId) {
		QueryWrapper<ProjectInfoRecords> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("xfrd_project_id", projectId);

		List<ProjectInfoRecords> list = projectInfoRecordsMapper.selectList(queryWrapper);

		List<User> userList = iUserService.list();
		for (ProjectInfoRecords projectInfoRecords : list) {
			Optional<User> optional = userList.stream()
					.filter(x -> x.getId().equals(projectInfoRecords.getCreateUserId())).findAny();
			if (optional.isPresent()) {
				User user = optional.get();

				projectInfoRecords.setCreateuserName(user.getNickName());
			}
		}

		return list;
	}

}
